package org.market.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.market.domain.strategy.repository.IStrategyRepository;
import org.market.domain.strategy.service.armory.IStrategyDispatch;
import org.market.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.market.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.market.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2025/2/23 下午11:27
 * @Version: 1.0
 */

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch strategyDispatch;

    public Long userCredit = 0L;


    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("责任链-权重过滤开始---userId:{},strategyId:{},ruleModel:{}", userId, strategyId,ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        Map<Long, String> analyticalValue = getAnalyticalValue(ruleValue);
        //根据用户id查询积分值
        if(analyticalValue == null ||analyticalValue.isEmpty()){
            //该用户不受约束直接放行
            return  null;
        }

        //转换位Keys的数组,并且进行排序,因为keySet之后为乱序
        ArrayList<Long> keys = new ArrayList<>(analyticalValue.keySet());
        Collections.sort(keys);

        //获取是否满足积分要求的最小值
        Long value = null;
        for (Long key : keys) {
            if (userCredit >= key){
                value = key;
            }
        }

        if (value != null) {
            log.info("责任链-权重过滤检测到积分达到要求---userId:{},strategyId:{}",userId,strategyId);
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValue.get(value));
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .awardRuleVale(DefaultChainFactory.logicMode.RULE_WEIGHT.getCode())
                    .build();
        }
        log.info("责任链-权重过滤结束~~~");
        return next().logic(userId, strategyId);
    }

    /**
     * 获取权重列表并且进行解析
     * 4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * @param ruleValue
     * @return
     */
    public Map<Long,String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueList = ruleValue.split(Constants.SPACE);
        HashMap<Long,String> map = new HashMap<>();
        for (String ruleWeight : ruleValueList) {
            if (ruleWeight == null || ruleWeight.isEmpty()) {
                return map;
            }

            String[] keyAndValue = ruleWeight.split(Constants.COLON);
            if (keyAndValue.length != 2){
                throw new IllegalArgumentException("rule_weight invalid input format" + ruleWeight);
            }

            map.put(Long.parseLong(keyAndValue[0]),ruleWeight);
        }
        return map;
    }

    @Override
    public String ruleModel() {
        return DefaultChainFactory.logicMode.RULE_WEIGHT.getCode();
    }
}
